package com.kt.sso.test.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.kt.sso.test.service.AuthService;
import io.micrometer.core.instrument.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Desc:
 *
 * @author: keen
 * Date: 2020-06-21
 * Time: 15:24
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @PostMapping("/signIn")
    public Map signIn(@RequestParam Map<String, String> args, HttpServletRequest request) {
        String username = args.get("username");
        String password = args.get("password");
        Map<String, Object> tokenMap = authService.getToken(username, password);
        String jti = (String) tokenMap.get("jti");
        try {
            saveToken(tokenMap);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        saveCookie(jti);
        return tokenMap;
    }

    private void saveToken(Map<String, Object> tokenMap) throws JsonProcessingException {
        String key = "user_token:" + tokenMap.get("jti");
        Integer ttl = (Integer) tokenMap.get("expires_in");
        String content = objectMapper.writeValueAsString(tokenMap);
        stringRedisTemplate.boundValueOps(key).set(content, ttl, TimeUnit.SECONDS);
        Long expire = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
        log.info("expire:{}", expire);
    }

    private void saveCookie(String token) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        Cookie cookie = new Cookie("uid", token);
        cookie.setMaxAge(-1);
        cookie.setDomain("localhost");
        cookie.setPath("/");
        cookie.setHttpOnly(false);
        response.addCookie(cookie);
    }
}
